package spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/file")
@Transactional
public class FileController {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
    @RequestMapping(value = "/upload")
    @ResponseBody
    public void upload(MultipartFile[] files, HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
        if (files.length == 0){
            req.setAttribute("result", "上传文件个数为0 或 上传文件失败！");
            req.getRequestDispatcher("/login.jsp").forward(req,response);
            return;
        }
        String format = simpleDateFormat.format(new Date());
        String realpath = req.getServletContext().getRealPath("/files");
        System.out.println(realpath);
        File folder = new File(realpath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String[] demo1 = new String[files.length];
        int i=0;
        for(MultipartFile file:files){
            try{
                String oldname = file.getOriginalFilename();
                String name = UUID.randomUUID().toString()+oldname.substring(oldname.lastIndexOf("."));
                file.transferTo(new File(folder,name));
                String url = req.getScheme()+ "://"+req.getServerName() +":"+req.getServerPort() +"/files/" +name;
                System.out.println(url);
                demo1[i] = url;
                i++;
            }catch (Exception e){
                req.setAttribute("result", "上传文件个数为0 或 上传文件失败！");
                req.getRequestDispatcher("/login.jsp").forward(req,response);
                return;
            }
        }
        req.setAttribute("result", i + "个文件上传成功，登陆后可下载！");
        req.getRequestDispatcher("/login.jsp").forward(req,response);
    }
    @RequestMapping(value = "/download")
    @ResponseBody
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String realPath = request.getServletContext().getRealPath("/files");
        FileInputStream is = new FileInputStream(new File(realPath, fileName));
        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("content-disposition", "attachment;fileName=" + fileName);
        ServletOutputStream os = response.getOutputStream();
        int len;
        byte[] b = new byte[1024];
        while(true){
            len = is.read(b);
            if(len == -1) break;
            os.write(b, 0, len);
        }
        os.close();
        is.close();
    }
}
